Solves RuntimeError in Torch optimization, and NaN in scaled torch optimization#485
Merged
manuelFragata merged 1 commit intomasterfrom Feb 21, 2026
Merged
Conversation
Codecov Report✅ All modified and coverable lines are covered by tests. @@ Coverage Diff @@
## master #485 +/- ##
==========================================
+ Coverage 93.16% 93.18% +0.01%
==========================================
Files 304 304
Lines 17951 17963 +12
==========================================
+ Hits 16724 16738 +14
+ Misses 1227 1225 -2
🚀 New features to boost your workflow:
|
Owner
|
Thanks for applying these fixes! Nice catches. Kramer |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
The issue #483 is solved with the following logic:
1. Fix
TorchBaseOptimizerand parameter space consistencyFiles:
base.pyin torch optimizerstorch optimizers now work consistently in scaled parameter space, matching the scipy optimizers:
var.variable.get_value()→var.value(scaled)var.variable.update_value(param)→var.update(param)(inverse-scales internally)var.bounds(unchanged — already scaled)This ensures
_apply_bounds()clamps parameters in the same space they live in, preventing catastrophic value corruption.The issue #484 is solved with the following logic:
n/kcaching causesRuntimeErrorunder torch + grad modeWhen using the torch backend with gradient tracking enabled, calling
.backward()more than once during optimization raises:RuntimeError: Trying to backward through the graph a second time
(or directly access saved tensors after they have already been freed).
Why this happens: When
BaseMaterial.n()computes a refractive index under torch, the result is a tensor connected to a computation graph. If that tensor is cached and reused in a later forward pass, the new.backward()call tries to traverse the old (already freed) graph — causing the RuntimeError.The previous fix I applied privately bypassed the cache entirely whenever be.grad_mode.requires_grad is True:
This solved the RuntimeError but introduced two problems:
Performance: Every call recomputes the refractive index from scratch, even for identical wavelengths. During optimization, the same materials are queried thousands of times — a significant penalty.
Broke the caching test: test_caching[backend=torch] failed because the cache was never populated.
The fix in this PR user a more robust approach - before caching, check what kind of result we got:
If the result requires grad (i.e., the index itself is an optimization variable like
IdealMaterial(n=nn.Parameter(...))): skip cache, return fresh — gradient flow must be preserved.If the result does not require grad (i.e., it's a constant like
Material("N-BK7")): detach and cache —.detach()severs the link to the old computation graph so it can't cause the RuntimeError, and caching avoids redundant recomputation.This gives us correct gradient behavior, no RuntimeError, and full caching performance for the common case where materials are constants.
Fixes #483 and #484